/*************************************************************************
    > File Name: tick_demo.c
    > Author: Xing.Dai
    > Mail: Xing.Dai@aliyun.com 
    > Created Time: 2017-05-24 23:07
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>

void countdown(int signum)
{
	static int num = 10;
	printf("%d..", num--);
	fflush(stdout);
	if(num < 0){
		printf("DONE!\n");
		exit(0);
	}
}

/**
 * @Synopsis  
 *
 * @Param n_msecs: millisecond.
 *
 * @Returns   
 */
int set_ticker(int n_msecs)
{
	struct itimerval new_timeset;
	long n_sec, n_usecs;

	n_sec = n_msecs / 1000;					/* int part */
	n_usecs = (n_msecs % 1000) * 1000L;		/* remainder */
	
	new_timeset.it_interval.tv_sec = n_sec;
	new_timeset.it_interval.tv_usec = n_usecs;

	new_timeset.it_value.tv_sec = n_sec;
	new_timeset.it_value.tv_usec = n_usecs;

	return setitimer(ITIMER_REAL, &new_timeset, NULL);


}

int main()
{
	signal(SIGALRM, countdown);
	
	if(set_ticker(500) == -1)
		perror("set_ticker");
	else {
		while(1){
			pause();
		}
	}

	return 0;
}
